﻿using Servo_Tool.entity;
using Servo_Tool.cache;
using Servo_Tool.client;
using Servo_Tool.constant;
using Servo_Tool.dal;
using Servo_Tool.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Servo_Tool.log;
using Servo_Tool.handler;

namespace Servo_Tool.init
{
    public class InitLoading
    {
        private readonly string unitNo;
        public event Action<string, string, string> ShowMessageUpdated;
        //事件判定
        private readonly JudgeHandler judgeHandler;

        public InitLoading(string unitNo, JudgeHandler judgeHandler)
        {
            this.unitNo = unitNo;
            this.judgeHandler = judgeHandler;
        }

        /**
         * 定时任务,循环执行
         */
        public void CircleListening()
        {
            if (!GlobalCachePool.s7_clinet.TryGetValue("HK_CV", out S7NetClient client))
            {
                return;
            }
            List<PlcItemEntity> newItems = new List<PlcItemEntity>();

            //循环监听
            while (true)
            {
                newItems.Clear();
                //获取缓存中的PLC_ITEM进行监听
                if (!GlobalCachePool.plcItems_dict.TryGetValue("HK_CV", out List<PlcItemEntity> items))
                {
                    return;
                }
                foreach (PlcItemEntity item in items)
                {
                    string value = client.ReadData(item.DB_BLOCK, item.ITEM_ADR, (byte)item.OFFSET, item.DISPLAY_TYPE, item.DATA_LEN);
                    //是否为心跳点,如果是则心跳0/1切换
                    if ("HEART_BEAT".Equals(item.ITEM_NO))
                    {
                        int heart = value.Equals("0") ? 1 : 0;
                        client.WriteData(item.DB_BLOCK, item.ITEM_ADR, item.OFFSET, item.DISPLAY_TYPE, heart);
                    }
                    //判断与旧值是否相同
                    if (value.Equals(item.ITEM_VALUE))
                    {
                        continue;
                    }

                    if (!"HEART_BEAT".Equals(item.ITEM_NO))
                    {
                        ShowMessage("0", $"[{item.ITEM_NAME}]值变化!当前为[{value}]");
                    }

                    item.OLD_VALUE = item.ITEM_VALUE;
                    item.ITEM_VALUE = value;
                    item.UPDATE_DATE = DateTime.Now;

                    newItems.Add(item);
                }
                if (newItems.Count > 0)
                {
                    DBFactory.BatchUpdateOfItem(newItems);
                }
                //做事件判断
                judgeHandler.JudgeEventByCache();
                Thread.Sleep(1000);
            }
        }

        public void InitListenChange()
        {
            List<PcItemEntity> pcItems = DBFactory.QueryList<PcItemEntity>(SqlConstant.PC_ITEM_SQL);
            if (pcItems == null || pcItems.Count == 0)
            {
                return;
            }

            pcItems.ForEach(pc =>
            {
                ShowMessage("0", $"[{pc.ITEM_NAME}]的值变更为[{pc.ITEM_VALUE}]");

                //将值写入(通过unitNo找到设备,调用其write方法)
                if (GlobalCachePool.s7_clinet.TryGetValue("HK_CV", out S7NetClient client))
                {
                    try
                    {
                        client.WriteData(pc.DB_BLOCK, pc.ITEM_ADR, pc.OFFSET, pc.DISPLAY_TYPE, pc.ITEM_VALUE);
                    }
                    catch (Exception e)
                    {
                        LoggerHelper.Error("手动修改数据写入失败!", e);
                    }
                }
                //无论是否成功都将值重置为0
                pc.STATUS = 0;
                pc.ITEM_VALUE = "";
                pc.UPDATE_DATE = DateTime.Now;
            });

            DBFactory.BatchUpdateOfPc(pcItems);
        }

        public void ShowMessage(string code, string msg)
        {
            ShowMessageUpdated?.Invoke("HK_CV", code, msg);
        }
    }
}
